package com.example.demoappsocketserver;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import androidx.annotation.NonNull;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketServerOld2 {
    private static SocketServerOld2 sSocketServerOld2;
    private ServerSocket mServer;
    private Socket mSocket;
    private int mPort = 0;
    private Thread mListenThread;
    private InputStream mInputStream;
    private OutputStream mOutputStream;
    private ConnectListener mListener;


    public static SocketServerOld2 getInstance() {
        if (sSocketServerOld2 == null) {
            sSocketServerOld2 = new SocketServerOld2();
        }
        return sSocketServerOld2;
    }

    Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 100:
                    if (mListener != null) {
                        mListener.onReceiveData(msg.getData().getString("data"));
                    }
                    break;
                default:
                    break;
            }
        }
    };

    public void initListen(final int port) {
        this.mPort = port;
        try {
            mServer = new ServerSocket(port);
            if (mListenThread == null) {
                mListenThread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        listen();
                    }
                });
                mListenThread.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
            if (mListener != null) {
                mListener.onCreateListenerFail(e.getMessage());
            }
        }
    }

    private void listen() {
        try {
            mSocket = mServer.accept();
            mInputStream = mSocket.getInputStream();
            if (mInputStream != null) {
                byte[] buffer = new byte[1024];
                int len = -1;
                //读取数据
                while ((len = mInputStream.read(buffer)) != -1) {
                    String data = new String(buffer, 0, len);
                    Message message = new Message();
                    message.what = 100;
                    Bundle bundle = new Bundle();
                    bundle.putString("data", data);
                    message.setData(bundle);
                    mHandler.sendMessage(message);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            mSocket.isClosed();
        }
    }


    /**
     * 发送数据
     *
     * @param data
     */
    public void sendData(final String data) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    mOutputStream = mSocket.getOutputStream();
                    if (mOutputStream != null) {
                        mOutputStream.write(data.getBytes());
//                        mOutputStream.flush();
                    }
                } catch (Exception e) {
                    if (mListener != null) {
                        mListener.onBrokenPipe(e.getMessage());
                    }
                    // 释放连接资源，重新监听
                    mServer = null;
                    mSocket = null;
                    mListenThread = null;
                    if (mPort != 0) {
                        initListen(mPort);
                    }
                }
            }
        }).start();
    }

    public void setOnConnectListener(ConnectListener connectListener) {
        this.mListener = connectListener;
    }

    public interface ConnectListener {
        /**
         * 创建监听错误
         *
         * @param error 错误信息
         */
        void onCreateListenerFail(String error);

        /**
         * 接收数据
         *
         * @param data 接收的数据
         */
        void onReceiveData(String data);

        /**
         * 连接断开，重连
         *
         * @param message 连接断开信息
         */
        void onBrokenPipe(String message);
    }


}
